<template>
  <div class="patient-detail-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span v-if="!error">{{ patient ? patient.patient_name + ' - 患者详情' : '患者详情' }}</span>
          <span v-else class="error-title">患者不存在</span>
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-loading v-model="loading" text="正在加载患者信息..." />
      </div>
      
      <div v-else-if="patient && !error" class="detail-content">
        <!-- 患者基本信息 -->
        <el-descriptions class="info-section" title="基本信息">
          <el-descriptions-item label="患者ID">{{ patient.patient_id }}</el-descriptions-item>
          <el-descriptions-item label="患者姓名">{{ patient.patient_name }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ patient.id_card }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ patient.gender }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ formatDate(patient.birth_date) }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ calculateAge(patient.birth_date) }}岁</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ patient.phone_number }}</el-descriptions-item>
          <el-descriptions-item label="住址" :span="3">{{ patient.address }}</el-descriptions-item>
          <el-descriptions-item label="血型">{{ patient.blood_type }}</el-descriptions-item>
          <el-descriptions-item label="过敏史" :span="3">{{ patient.allergies || '无' }}</el-descriptions-item>
          <el-descriptions-item label="既往病史" :span="4">{{ patient.past_history || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(patient.creation_time) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ patient.update_time ? formatDateTime(patient.update_time) : '暂无更新' }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 操作按钮 -->
        <div class="operation-section">
          <el-button type="warning" @click="editPatient">编辑患者信息</el-button>
          <el-button type="success" @click="addStrokeEvent">添加卒中事件</el-button>
          <el-button type="info" @click="exportPatientData">导出患者数据</el-button>
        </div>
        
        <!-- 患者卒中事件列表 -->
        <el-card class="events-card">
          <template #header>
            <div class="card-header">
              <span>卒中事件记录</span>
              <el-button type="primary" size="small" @click="addStrokeEvent">新增事件</el-button>
            </div>
          </template>
          
          <el-table 
            :data="patientStrokeEvents" 
            style="width: 100%"
            border
          >
            <el-table-column prop="event_id" label="事件ID" width="100" />
            <el-table-column prop="onset_time" label="发病时间" width="180" />
            <el-table-column prop="admission_time" label="入院时间" width="180" />
            <el-table-column prop="affected_location" label="发病部位" width="120" />
            <el-table-column prop="severity" label="严重程度" width="100" />
            <el-table-column prop="event_type" label="事件类型" width="100" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="viewStrokeEventDetail(row.event_id)">详情</el-button>
                <el-button type="danger" size="small" @click="deleteStrokeEvent(row.event_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="patientStrokeEvents.length === 0" class="empty-state">
            <el-empty description="暂无卒中事件记录" />
          </div>
        </el-card>
      </div>
      
      <div v-else class="empty-state error-state">
        <div class="error-icon">
          <el-icon><CircleCloseFilled /></el-icon>
        </div>
        <h3 class="error-heading">{{ error ? '患者不存在或已被删除' : '无法加载患者数据' }}</h3>
        <p class="error-message">{{ error ? '您请求的患者ID可能有误，或者该患者已被删除。' : '请检查网络连接后重试。' }}</p>
        <div class="error-actions">
          <el-button type="primary" @click="loadPatientData">重新加载</el-button>
          <el-button @click="goBack">返回患者列表</el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 编辑患者对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑患者信息"
      width="700px"
    >
      <el-form 
        :model="editForm" 
        ref="editFormRef" 
        label-width="120px"
        :rules="formRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者姓名" prop="patient_name">
              <el-input v-model="editForm.patient_name" placeholder="请输入患者姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="id_card">
              <el-input v-model="editForm.id_card" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="editForm.gender" placeholder="请选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birth_date">
              <el-date-picker
                v-model="editForm.birth_date"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone_number">
              <el-input v-model="editForm.phone_number" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="血型" prop="blood_type">
              <el-select v-model="editForm.blood_type" placeholder="请选择血型">
                <el-option label="A" value="A"></el-option>
                <el-option label="B" value="B"></el-option>
                <el-option label="AB" value="AB"></el-option>
                <el-option label="O" value="O"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="住址" prop="address">
              <el-input 
                v-model="editForm.address" 
                placeholder="请输入住址"
                type="textarea"
                rows="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="过敏史" prop="allergies">
              <el-input 
                v-model="editForm.allergies" 
                placeholder="请输入过敏史，如无请填写'无'"
                type="textarea"
                rows="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="既往病史" prop="past_history">
              <el-input 
                v-model="editForm.past_history" 
                placeholder="请输入既往病史，如无请填写'无'"
                type="textarea"
                rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CircleCloseFilled } from '@element-plus/icons-vue'
import { patientAPI, strokeEventAPI } from '../api'

const router = useRouter()
const route = useRoute()

// 状态数据
const loading = ref(true)
const patient = ref(null)
const allStrokeEvents = ref([])
const editDialogVisible = ref(false)
const editFormRef = ref()
const error = ref(false)

// 表单验证规则
const formRules = {
  patient_name: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' }
  ],
  id_card: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: '请输入有效的身份证号',
      trigger: 'blur'
    }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birth_date: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  phone_number: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur'
    }
  ]
}

// 编辑表单
const editForm = ref({
  patient_id: '',
  patient_name: '',
  id_card: '',
  gender: '',
  birth_date: '',
  phone_number: '',
  address: '',
  blood_type: '',
  allergies: '',
  past_history: ''
})

// 过滤出当前患者的卒中事件
const patientStrokeEvents = computed(() => {
  return allStrokeEvents.value.filter(event => event.patient_id === patient.value?.patient_id)
})

// 获取患者详情
const getPatientDetail = async () => {
  const patientId = route.params.id
  if (!patientId) {
    loading.value = false
    error.value = true
    ElMessage.warning('患者ID无效')
    return
  }
  
  loading.value = true
  error.value = false
  try {
    // 获取患者信息
    const patients = await patientAPI.getPatients()
    
    // 查找匹配的患者，确保ID类型一致
    const patientData = patients.find(p => {
      // 处理不同格式的患者ID
      if (p.patient_id !== undefined) {
        return p.patient_id === parseInt(patientId)
      } else if (p['患者ID'] !== undefined) {
        return p['患者ID'] === parseInt(patientId)
      }
      return false
    })
    
    if (!patientData) {
      error.value = true
      ElMessage.warning('患者不存在')
      return
    }
    
    // 规范化患者数据格式，确保字段名一致
    patient.value = {
      patient_id: patientData.patient_id || patientData['患者ID'],
      patient_name: patientData.patient_name || patientData['姓名'],
      id_card: patientData.id_card || patientData['身份证号'],
      gender: patientData.gender || patientData['性别'],
      birth_date: patientData.birth_date || patientData['出生日期'],
      phone_number: patientData.phone_number || patientData['联系方式'],
      address: patientData.address || patientData['常住地址'],
      blood_type: patientData.blood_type || patientData['血型'] || '未知',
      allergies: patientData.allergies || patientData['过敏史'] || '无',
      past_history: patientData.past_history || patientData['既往病史'] || '无',
      creation_time: patientData.creation_time || patientData['created_at'] || new Date().toISOString(),
      update_time: patientData.update_time || patientData['updated_at']
    }
    
    // 获取所有卒中事件
    const events = await strokeEventAPI.getEvents()
    
    // 规范化卒中事件数据格式
    allStrokeEvents.value = events.map(event => ({
      event_id: event.event_id || event['事件ID'],
      patient_id: event.patient_id || event['患者ID'],
      onset_time: event.onset_time || event['发病时间'],
      admission_time: event.admission_time || event['入院时间'],
      discharge_time: event.discharge_time || event['出院时间'],
      affected_location: event.affected_location || event['发病部位'],
      severity: event.severity || event['严重程度'],
      event_type: event.event_type || event['事件类型'],
      recurrence: event.recurrence || event['是否复发'],
      clinical_manifestations: event.clinical_manifestations || event['临床表现'],
      imaging_results: event.imaging_results || event['影像学检查结果'],
      creation_time: event.creation_time || event['创建时间'],
      update_time: event.update_time || event['更新时间']
    }))
    
  } catch (err) {
    error.value = true
    ElMessage.error('获取患者详情失败')
    console.error('获取患者详情失败:', err)
  } finally {
    loading.value = false
  }
}

// 返回患者列表
const goBack = () => {
  router.push('/patients')
}

// 编辑患者信息
const editPatient = () => {
  editForm.value = { ...patient.value }
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    
    const updatedPatient = {
      ...editForm.value,
      update_time: new Date().toISOString()
    }
    
    await patientAPI.updatePatient(updatedPatient)
    ElMessage.success('患者信息更新成功')
    
    patient.value = updatedPatient
    editDialogVisible.value = false
  } catch (error) {
    if (error !== false) { // 非表单验证错误
      ElMessage.error('更新失败，请重试')
      console.error('更新失败:', error)
    }
  }
}

// 添加卒中事件
const addStrokeEvent = () => {
  router.push(`/stroke-events/add?patientId=${patient.value.patient_id}`)
}

// 查看卒中事件详情
const viewStrokeEventDetail = (eventId) => {
  router.push(`/stroke-events/${eventId}`)
}

// 删除卒中事件
const deleteStrokeEvent = async (eventId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该卒中事件记录吗？此操作不可撤销！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await strokeEventAPI.deleteEvent(eventId)
    ElMessage.success('卒中事件记录已删除')
    
    // 更新本地数据
    allStrokeEvents.value = allStrokeEvents.value.filter(event => event.event_id !== eventId)
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

// 导出患者数据
const exportPatientData = () => {
  // 这里可以实现患者数据导出功能
  ElMessage.success('数据导出功能待实现')
}

// 工具方法
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const calculateAge = (birthDateString) => {
  if (!birthDateString) return 0
  const birthDate = new Date(birthDateString)
  const today = new Date()
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  
  return age
}

// 添加一个方法，允许用户手动加载数据
const loadPatientData = () => {
  getPatientDetail()
}

// 组件挂载时自动获取数据
onMounted(() => {
  getPatientDetail()
})
</script>

<style scoped>
.patient-detail-container {
  padding: 20px;
  background-color: #1a1a1a;
  min-height: 100vh;
}

.patient-detail-container {
  background-color: #ffffff;
  min-height: 100vh;
  padding: 20px;
}

.page-card {
  margin-bottom: 20px;
  background-color: #ffffff;
  border: 1px solid #ddd;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
}

/* 确保标题文字为黑色 */
.card-header span {
  color: #000000 !important;
}

.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-content {
  width: 100%;
}

.info-section {
  margin-bottom: 20px;
}

:deep(.el-descriptions) {
  --el-descriptions-bg-color: #ffffff;
  --el-descriptions-border-color: #ddd;
}

:deep(.el-descriptions__title) {
  color: #333;
  margin-bottom: 20px;
}

:deep(.el-descriptions-item__label) {
  color: #666;
  font-weight: 500;
}

:deep(.el-descriptions-item__content) {
  color: #333;
}

.operation-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  display: flex;
  gap: 10px;
  border: 1px solid #e9ecef;
}

.events-card {
  margin-top: 20px;
  background-color: #ffffff;
  border: 1px solid #ddd;
}

:deep(.el-table) {
  --el-table-bg-color: #ffffff;
  --el-table-header-bg-color: #f5f5f5;
  --el-table-border-color: #ddd;
  --el-table-text-color: #000000;
}

:deep(.el-table thead) {
  --el-table-header-cell-text-color: #000000;
}

:deep(.el-table tbody) {
  --el-table-row-hover-bg-color: #f5f5f5;
  --el-table-row-current-bg-color: #e6f7ff;
}

:deep(.el-empty__text) {
  color: #999;
}

.empty-state {
  padding: 40px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #000000;
}

.error-state {
  padding: 60px 0;
  text-align: center;
}

.error-icon {
  font-size: 60px;
  color: #f56c6c;
  margin-bottom: 20px;
}

.error-title {
  color: #f56c6c;
  font-weight: bold;
}

.error-heading {
  margin: 10px 0;
  color: #303133;
  font-size: 18px;
}

.error-message {
  color: #606266;
  margin-bottom: 30px;
}

.error-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

/* 对话框样式 */
:deep(.el-dialog__title) {
  color: #fff;
}

:deep(.el-dialog__body) {
  background-color: #242424;
  color: #fff;
}

:deep(.el-dialog__footer) {
  background-color: #242424;
  border-top: 1px solid #333;
}

:deep(.el-form-item__label) {
  color: #d0d0d0;
}

:deep(.el-input__wrapper) {
  background-color: #333;
  border-color: #444;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__inner) {
  color: #fff;
}

:deep(.el-input__placeholder) {
  color: #999;
}

:deep(.el-select__wrapper) {
  background-color: #333;
  border-color: #444;
}

:deep(.el-select__wrapper:hover) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
}

:deep(.el-select__inner) {
  color: #fff;
}

:deep(.el-select__placeholder) {
  color: #999;
}

:deep(.el-date-editor .el-input__wrapper) {
  background-color: #333;
  border-color: #444;
}

:deep(.el-date-editor .el-input__inner) {
  color: #fff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .patient-detail-container {
    padding: 10px;
    background-color: #ffffff;
  }
  
  .operation-section {
    flex-wrap: wrap;
  }
}
</style>